package com.uni.crawl.service.impl.crawl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.toolkit.MPJWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.uni.crawl.mapper.CrawlDataMapper;
import com.uni.crawl.model.entity.crawl.CrawlData;
import com.uni.crawl.model.entity.crawl.CrawlInstance;
import com.uni.crawl.model.entity.crawl.CrawlNamespace;
import com.uni.crawl.model.entity.crawl.CrawlTemplate;
import com.uni.crawl.model.query.crawl.CrawlDataPageQuery;
import com.uni.crawl.model.vo.crawl.CrawlDataVO;
import com.uni.crawl.service.PageQueryUtils;
import com.uni.crawl.service.crawl.CrawlDataService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 爬虫数据 服务实现类
 * </p>
 *
 * @author JervisPG
 * @since 2023-12-16
 */
@Service
public class CrawlDataServiceImpl extends MPJBaseServiceImpl<CrawlDataMapper, CrawlData> implements CrawlDataService {

    @Override
    public Page<CrawlDataVO> getPage(CrawlDataPageQuery pageQuery) {
        String nsCode = pageQuery.getNsCode();
        String tmplCode = pageQuery.getTmplCode();

        MPJLambdaWrapper<CrawlData> wp = MPJWrappers.lambdaJoin();
        wp.selectAll(CrawlData.class);
        wp.select(CrawlNamespace::getNsName);
        wp.select(CrawlTemplate::getTmplName);

        wp.leftJoin(CrawlNamespace.class, CrawlNamespace::getNsCode, CrawlData::getNsCode);
        wp.leftJoin(CrawlTemplate.class, CrawlTemplate::getTmplCode, CrawlData::getTmplCode);

        wp.eq(Objects.nonNull(pageQuery.getId()), CrawlData::getId, pageQuery.getId());
        wp.eq(Objects.nonNull(pageQuery.getInstanceId()), CrawlData::getInstanceId, pageQuery.getInstanceId());
        wp.eq(Objects.nonNull(pageQuery.getQueueId()), CrawlData::getQueueId, pageQuery.getQueueId());
        wp.eq(StrUtil.isNotEmpty(nsCode), CrawlInstance::getNsCode, nsCode);
        wp.like(StrUtil.isNotEmpty(tmplCode), CrawlInstance::getTmplCode, tmplCode);
        wp.eq(Objects.nonNull(pageQuery.getInstanceStatus()), CrawlInstance::getInstanceStatus, pageQuery.getInstanceStatus());
        PageQueryUtils.wrapTimeRange(wp, CrawlData::getCreateTime, pageQuery);

        wp.orderByDesc(CrawlData::getId);

        return selectJoinListPage(PageQueryUtils.getPage(pageQuery), CrawlDataVO.class, wp);
    }
}
